package main

import (
	"ginadmin/app/config"
	"ginadmin/app/dao"
	"ginadmin/app/middleware"
	"ginadmin/routers"
	"path/filepath"
	"strings"

	"github.com/gin-contrib/multitemplate"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
)

func LoadTemplates(templatesDir string) multitemplate.Renderer {

	r := multitemplate.NewRenderer()

	layouts, err := filepath.Glob(templatesDir + "/layout/*")

	if err != nil {
		panic("layout加载失败:" + err.Error())
	}

	includes, err := filepath.Glob(templatesDir + "/**/*")

	if err != nil {
		panic("其他模板加载失败:" + err.Error())
	}

	for _, include := range includes {
		layoutCopy := make([]string, len(layouts))
		copy(layoutCopy, layouts)
		files := append(layoutCopy, include)

		//兼容win下目录处理
		include = strings.ReplaceAll(include, "\\", "/")

		s := strings.Split(include, "/")

		if s[2] != "layout" {
			r.AddFromFiles(s[2]+"/"+filepath.Base(include), files...)
		}

		//r.AddFromFiles(filepath.Base(include), files...)
	}

	return r
}

func GinLoadHtml(v *gin.Engine) {

	//加载后台模板文件
	//v.LoadHTMLGlob("views/admin/**/*")

	v.HTMLRender = LoadTemplates("./views/admin")

	//加载静态文件
	v.Static("/static", "public/static")
}

func main() {

	//加载配置文件
	config.GetEnv()

	//初始化mysql
	dao.InitMysql()

	defer dao.Close()

	v := gin.Default()
	//v.ForwardedByClientIP = true

	//session初始化
	store := cookie.NewStore([]byte("abc123"))

	v.Use(sessions.Sessions("sessionId", store))

	//加载模板、静态文件
	GinLoadHtml(v)

	//加载全局中间件
	v.Use(middleware.AllowMiddleware())

	//加载默认路由
	routers.DefaultRouter(v)

	//加载后台路由
	routers.AdminRouter(v)

	v.Run()
}
